// 改为复用全局请求封装 utils/request.js（与你们登录/拦截器一致）
import request, { get, post, put, del } from '@/utils/request'

// 导出API方法
export default {
  // 查询资产列表
  listAsset(query = {}) {
    return get('/system/asset/list', query)
  },
  // 查询资产详细
  getAsset(assetNo) {
    return get(`/system/asset/${assetNo}`)
  },
  // 获取资产统计信息
  getAssetStatistics() {
    return get('/system/asset/statistics')
  },
  // 获取资产维修历史（后端接口：/system/asset/repairHistory）
  getAssetRepairHistory(query = {}) {
    const params = {
      pageNum: query.pageNum || 1,
      pageSize: query.pageSize || 10,
      assetNo: query.assetNo,
      startDate: query.startDate,
      endDate: query.endDate
    }
    return get('/system/asset/repairHistory', params)
  },
  // 上传资产图片，返回文件名
  uploadAssetImage(filePath) {
    return new Promise((resolve, reject) => {
      try {
        const baseURL = (uni.getStorageSync('BASE_URL') || 'http://127.0.0.1:8081').replace(/\/$/, '')
        const token = uni.getStorageSync('token') || uni.getStorageSync('Authorization') || uni.getStorageSync('Admin-Token') || ''
        
        // 使用MinIO上传接口
        const uploadUrl = baseURL + '/minio/upload'
        console.log('资产使用MinIO上传接口:', uploadUrl)
        
        uni.uploadFile({
          url: uploadUrl,
          filePath,
          name: 'file',
          fileType: 'image',
          header: {
            Authorization: token ? `Bearer ${token}` : undefined,
            Token: token
          },
          success: (res) => {
            console.log('资产MinIO上传响应:', res)
            try {
              const data = JSON.parse(res.data || '{}')
              const ok = ((res.statusCode === 200 || res.statusCode === 201)) && (data.code === undefined || data.code === 200)
              const fileName = data?.data?.fileName || data?.data?.name || data?.fileName || data?.name || data?.data
              if (ok && fileName) {
                console.log('资产MinIO上传成功，文件名:', fileName)
                return resolve(String(fileName))
              }
              reject(data)
            } catch (e) {
              if (res.statusCode === 200 && typeof res.data === 'string') {
                console.log('资产MinIO上传成功，直接返回:', res.data)
                return resolve(res.data)
              }
              reject(res)
            }
          },
          fail: (error) => {
            console.log('资产MinIO上传失败:', error)
            reject(error)
          }
        })
      } catch (e) { reject(e) }
    })
  },
  // 删除资产
  delAsset(assetNo) {
    return del(`/system/asset/${assetNo}`)
  },
  
  // 更新资产状态
  updateAssetStatus(assetNo, statusCode) {
    return put('/system/asset/status', {
      assetNo: assetNo,
      statusCode: statusCode
    })
  },
  
  // 批量更新资产状态
  batchUpdateAssetStatus(assetNos, statusCode) {
    return put('/system/asset/batchStatus', {
      assetNos: assetNos,
      statusCode: statusCode
    })
  }
}